<template>
    <div class="editProcess">
        <el-dialog :visible.sync="editProcessVisible" width="800px" @close='handleClose' :close-on-click-modal='false'>
            <span class="title" slot="title">编辑工序</span>
            <div class="dialogBody">
                <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px" size="mini">
                    <el-form-item label="工序编号" prop="processCode">
                        <el-input v-model="editForm.processCode" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="工序名称" prop="processName">
                        <el-input v-model="editForm.processName" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="报工权限" prop="permissionsName">
                        <el-select v-model="editForm.permissionsName" multiple filterable remote disabled>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="报工数配比" prop="rate">
                        <el-input v-model="editForm.rate" @input='rateInput'></el-input>
                    </el-form-item>
                    <el-form-item label="不良品项列表" prop="badProductList">
                        <el-select v-model="editForm.badProductList" multiple filterable remote disabled>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="计划数" prop="planedNumber">
                        <el-input v-model="editForm.planedNumber" @input='planNumInput'></el-input>
                    </el-form-item>
                    <el-form-item label="良品数" prop="goodProductNumber">
                        <el-input v-model="editForm.goodProductNumber" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="不良品数" prop="badProductNumber">
                        <el-input v-model="editForm.badProductNumber" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="计划开始/结束时间" prop="planedTime">
                        <el-date-picker v-model="editForm.planedTime" type="datetimerange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm"
                            :picker-options="pickerOptions"
                            :default-time="['00:00:00', '23:59:00']" :clearable="false">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="实际开始/结束时间" prop="actualTime">
                        <el-date-picker v-model="editForm.actualTime" type="datetimerange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm"
                            :default-time="['00:00:00', '23:59:00']" disabled>
                        </el-date-picker>
                    </el-form-item>
                    <!-- ====================自定义==================== -->
                    <el-form-item v-for='(item, i) in customFiledList' :key="i" :label='item.chineseName'
                        :prop="item.id" v-show='hiddenRule(item)'>
                        <el-checkbox-group v-show="false" v-model="editForm[item.id]"></el-checkbox-group>
                        <template slot='label'>
                            <span style="color: red" v-show="requireRsterisk(item)">*</span>
                            {{ item.chineseName }}
                            <el-tooltip class="item" effect="dark" :content="item.tips" placement="top"
                                v-show='item.tips'>
                                <span class="iconfont icon-wenhao wenhao"></span>
                            </el-tooltip>
                        </template>
                        <formLibrary :formItem='item' @formItemHandle='formItemHandle' :defaultData="defaultData"
                            @uploadProgress='uploadProgress' ref='formLibrary'></formLibrary>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" @click='editProcessVisible = false'>取 消</el-button>
                <el-button type="primary" size="mini" @click='confirmAdd'>确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {
        loginUserMess
    } from '@/api/loginController'
    import {
        customFieldOther,
        fillFieldMess
    } from '@/api/customFieldController'
    import formLibrary from '@/components/formLibrary'
    export default {
        data() {
            var checkNum = (rule, value, callback) => {
                let tit
                tit = rule.field == 'rate' ? '报工数配比' : '计划数'
                let reg = new RegExp(`^\\d+(\\.\\d{1,6})?$`)
                if (value == '') {
                    return callback(new Error(`${tit}必填`));
                } else if (value == 0) {
                    return callback(new Error(`${tit}必须大于0`))
                } else if (!reg.test(value)) {
                    return callback(new Error('只能为数字类型且小数点后最多保留6位数字'))
                } else {
                    callback()
                }
            };
            return {
                editForm: {
                    processCode: '',
                    processName: '',
                    permissionsName: [],
                    rate: '',
                    badProductList: [],
                    planedNumber: '',
                    goodProductNumber: '',
                    badProductNumber: '',
                    planedTime: [],
                    actualTime: []
                },
                editRules: {
                    processCode: [{
                        required: true,
                    }],
                    processName: [{
                        required: true,
                    }],
                    permissionsName: [{
                        required: true,
                    }],
                    rate: [{
                        required: true,
                        validator: checkNum
                    }],
                    badProductList: [{
                        required: true,
                    }],
                    planedNumber: [{
                        required: true,
                        validator: checkNum
                    }],
                    planedTime: [{
                        required: true,
                    }],
                },
                pickerOptions:{
                    disabledDate: time => {
                        return time.getTime() < Date.parse(this.planTime[0] + '') || time.getTime() > Date.parse(this.planTime[1] + '')
                    }
                },
                editProcessVisible: false,
                rowIndex: 0,
                customFiledList: [],
                defaultData: [], // 自定义字段值
                customFiledData: [],
                customState: true, // 判断单选/复选 选值是否正确
                customErrorLabel: '', // 选值错误提示语
                // 关联属性信息
                relevanceProp: [],
                productInfo: {},
                userMess: {},
                uploadFlag: true
            }
        },
        components: {
            formLibrary
        },
        props: {
            planTime: {
                type: Array,
                default: () => []
            },
            planedNumber: [Number, Boolean]
        },
        watch: {
            editForm: {
                handler() {
                    this.hiddenRule('')
                },
                deep: true,
            }
        },
        methods: {
            // 自定义字段
            getCustomFieldOther() {
                customFieldOther({
                    type: 'processes'
                }).then(res => {
                    this.customFiledList = []
                    this.relevanceProp = []
                    if (res.code == 200) {
                        // 自定义字段数据
                        res.data.map(item => {
                            item.customFieldMess.objectsValue = item.objectsValue
                            this.customFiledList.push(item.customFieldMess)
                        })
                        // 添加自定义字段的校验规则(是否必填)
                        this.customFiledList.map(item => {
                            let r = item.hidden
                            item.hidden = r.replace(/\${工序./g, 'formItemData["').replace(/\}/g, '"]')
                                .replace(/\${用户信息./g, 'userFormItemData["')
                            item.id = item.id + ''
                            let obj = {}
                            if (JSON.parse(item.fieldAttribute).required && item.fieldType != 'inputNumber') {
                                obj[item.id] = [{
                                    required: true,
                                    message: item.chineseName + '不能为空'
                                }]
                            }else if(item.fieldType == 'inputNumber'){
                                const numberRule = (rule, v, callback) => {
                                    let tempValue = ''
                                    let index = String(this.editForm[item.id]).indexOf('.')
                                    tempValue = index != -1 ? String(this.editForm[item.id]).slice(0,index) : String(this.editForm[item.id])
                                    if (!this.editForm[item.id] && item.isRequired) {
                                        return callback(new Error(`${item.chineseName}不能为空！`));
                                    }else if(tempValue.length > 10){
                                        return callback(new Error('整数位最多支持10位数字'));
                                    }else if(this.editForm[item.id] != undefined && !(/^[0-9]+(.[0-9]{1,6})?$/.test(this.editForm[item.id]))){
                                        return callback(new Error('小数点后最多保留6位数字'));
                                    }else {
                                        callback()
                                    }
                                }
                                obj[item.id] = [{
                                    validator: numberRule,
                                    trigger:'blur'
                                }]
                            }
                            this.editRules = Object.assign(this.editRules, obj)
                            if (item.fieldType == 'relevanceProp') {
                                this.relevanceProp.push({
                                    id: item.id,
                                    objectFieldId: item.objectFieldId,
                                    type: item.correlationField
                                })
                            }
                        })
                        this.getLoginUserMess()
                    }
                })
            },
            // 用户信息
            getLoginUserMess(data) {
                loginUserMess(data).then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        this.userMess = res.data
                    }
                })
            },
            // 关联对象-字段信息
            getFillFieldMess(data, fillRule, n) {
                fillFieldMess(data).then(res => {
                    this.defaultData = []
                    for (let key in this.editForm) {
                        if (Number(key)) {
                            this.defaultData.push({
                                customFieldId: key,
                                value: this.editForm[key]
                            })
                        }
                    }
                    if (res.code == 200) {
                        // 如果该条数据有自定义字段
                        if (res.data.customFieldVos != null) {
                            /* 
                                遍历关联对象的填充规则
                                遍历该条数据的自定义字段列表
                                将填充规则中的来源值(from) 赋给 指定控件(to)
                            */
                            fillRule.map(item => {
                                let dataArr = []
                                let f = res.data.customFieldVos.find(res => {
                                    return res.customFieldId == item.from
                                })
                                if (f != undefined) {
                                    res.data.customFieldVos.map(k => {
                                        if (k.customFieldId == item.from) {
                                            this.editForm[item.to] = k.value
                                            this.defaultData = this.defaultData.filter(j => j
                                                .customFieldId != item.to)
                                            this.defaultData.push({
                                                customFieldId: item.to,
                                                value: k.value
                                            })
                                        }
                                    })
                                } else {
                                    this.editForm[item.to] = ''
                                    this.defaultData.map(k => {
                                        if (k.customFieldId == item.to) {
                                            let d = this.customFiledList.find(res => {
                                                return res.id == item.to
                                            })
                                            if (d.fieldType == 'picture' || d.fieldType ==
                                                'upload' || d.fieldType == 'selectChecked') {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: "[]"
                                                })
                                            } else {
                                                dataArr.push({
                                                    customFieldId: k.customFieldId,
                                                    value: ""
                                                })
                                            }
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: k.value
                                            })
                                        }
                                    })
                                    this.defaultData = dataArr
                                }
                            })
                        } else {
                            fillRule.map(item => {
                                let dataArr = []
                                this.editForm[item.to] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.to) {
                                        let d = this.customFiledList.find(res => {
                                            return res.id == item.to
                                        })
                                        if (d.fieldType == 'picture' || d.fieldType ==
                                            'upload' || d.fieldType == 'selectChecked') {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: "[]"
                                            })
                                        } else {
                                            dataArr.push({
                                                customFieldId: k.customFieldId,
                                                value: ""
                                            })
                                        }
                                    } else {
                                        dataArr.push({
                                            customFieldId: k.customFieldId,
                                            value: k.value
                                        })
                                    }
                                })
                                this.defaultData = dataArr
                            })
                        }
                        // 关联属性赋值
                        this.relevanceProp.map(item => {
                            if (item.objectFieldId == n) {
                                this.editForm[item.id] = res.data[item.type]
                                this.defaultData = this.defaultData.filter(j => j.customFieldId != item
                                    .id)
                                this.defaultData.push({
                                    customFieldId: item.id,
                                    value: res.data[item.type]
                                })
                            }
                        })
                    }
                })
            },
            // 自定义表单项数据--表单子组件传递的值
            formItemHandle(d) {
                // 子组件的值赋给表单
                this.$set(this.editForm, d.name, d.value)
                // 操作的是关联对象
                if (d.relevanceObject != undefined) {
                    if (d.relevanceObject.id) {
                        let data = {
                            id: d.relevanceObject.id,
                            type: d.relevanceObject.businessObject
                        }
                        this.getFillFieldMess(data, d.relevanceObject.fillRule, d.name)
                    } else {
                        this.customFiledList.map(item => {
                            if (item.objectFieldId == d.name) {
                                this.editForm[item.id] = ''
                                this.defaultData.map(k => {
                                    if (k.customFieldId == item.id || k.customFieldId == d.name) {
                                        k.value = ''
                                    }
                                })
                            }
                        })
                        for (let key in this.editForm) {
                            let ind = this.defaultData.findIndex(res => {
                                return res.customFieldId == key
                            })
                            if (ind != -1) {
                                this.$set(this.defaultData, ind, {
                                    customFieldId: key,
                                    value: this.editForm[key]
                                })
                            } else {
                                this.defaultData.push({
                                    customFieldId: key,
                                    value: this.editForm[key]
                                })
                            }
                        }
                    }
                }
            },
            // 自定义隐藏设置--隐藏条件触发
            hiddenRule(d) {
                let formItemData = {
                    '产品编号': this.editForm.code,
                    '产品名称': this.editForm.name,
                    '产品规格': this.editForm.specification,
                    '单位': this.unitName
                }
                let userFormItemData = {
                    '账号': this.userMess.account,
                    '姓名': this.userMess.name,
                    '手机号': this.userMess.mobile,
                    '角色': this.userMess.role,
                }
                this.customFiledList.map(item => {
                    if (formItemData[item.chineseName] == undefined) {
                        if (this.editForm[item.id] != undefined) {
                            formItemData[item.chineseName] = this.editForm[item.id]
                        } else {
                            formItemData[item.chineseName] = ''
                        }
                    }
                    if (userFormItemData[item.chineseName] == undefined) {
                        if (this.editForm[item.id] != undefined) {
                            userFormItemData[item.chineseName] = this.editForm[item.id]
                        } else {
                            userFormItemData[item.chineseName] = ''
                        }
                    }
                })
                let state = null
                try {
                    state = !eval(d.hidden)
                } catch {
                    state = true
                }
                //必填项字段若是被隐藏不校验
                if (this.editRules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        if(JSON.parse(d.fieldAttribute).required){ //inputNumber 必填 && 切换触发隐藏条件
                            d.isRequired = state
                        }
                    }else{
                        this.editRules[d.id][0].required = state
                    }
                }
                return state
            },
            requireRsterisk(d) {
                if (this.editRules[d.id]) {
                    if(d.fieldType == 'inputNumber'){
                        return JSON.parse(d.fieldAttribute).required || false
                    }else{
                        return this.editRules[d.id][0].required || false
                    }
                }
            },
            customData(v, data) {
                if (Number(v)) {
                    let id = ''
                    data.map(item => {
                        if (item.value == v) {
                            id = item.label
                        }
                    })
                    return id
                } else {
                    return v
                }
            },
            // 附件/图片上传是否完成
            uploadProgress(s) {
                this.uploadFlag = s
            },
            add(payload) {
                this.getCustomFieldOther()
                this.rowIndex = payload.index
                for (const key in payload.row) {
                    Object.keys(this.editForm).forEach(i => {
                        if (i == key) {
                            if (key == 'permissionsName' || key == 'badProductList') {
                                this.editForm[i] = payload.row[key].split(',')
                            } else {
                                this.editForm[i] = payload.row[key]
                            }
                        }
                    })
                    this.editForm.planedTime = [payload.row.planedStartTime, payload.row.planedEndTime]
                    this.editForm.actualTime = [payload.row.actualStartTime, payload.row.actualEndTime]
                }
                this.defaultData = []
                if (payload.row.customFieldVos != null) {
                    payload.row.customFieldVos.map(item => {
                        this.$set(this.editForm, item.customFieldId, item.value)
                        this.defaultData.push({
                            customFieldId: item.customFieldId,
                            value: item.value
                        })
                    })
                }
                this.editProcessVisible = true
                this.$nextTick(() => {
                    let bodyNode = document.querySelector('.dialogBody')
                    bodyNode.scrollTop = 0
                })
            },
            //报工数配比改变
            rateInput(n) {
                //报工数配比与计划数小数点后长度保持一致
                if (!this.planedNumber) return
                let index = n.indexOf('.')
                let strLength
                if (index != -1) strLength = n.substr(index + 1).length
                this.editForm.planedNumber = (this.planedNumber * n).toFixed(
                    n.substr(n.length - 1, 1) == '0' ? strLength - 1 : strLength)
            },
            //生产任务表格计划数改变
            planNumInput(n) {
                if (!this.planedNumber) return
                this.editForm.rate = (n / this.planedNumber).toFixed(6)
            },
            handleClose() {
                this.$refs.editForm.resetFields()
            },
            //确认
            confirmAdd() {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        let data = {
                            customFieldVos: []
                        }
                        let jsonForm = JSON.parse(JSON.stringify(this.editForm))
                        // 关联对象后，判断单选框/复选框关联过来的值是否存在
                        this.customState = true
                        this.customErrorLabel = ''
                        this.customFiledList.map(item => {
                            // 单选框
                            if (item.fieldType == 'selectRadio') {
                                if (jsonForm[item.id] != '' && jsonForm[item.id] !=
                                    undefined) {
                                    let s = JSON.parse(item.checkBox).find(res => {
                                        return jsonForm[item.id] == res.value
                                    })
                                    if (s == undefined) {
                                        this.customState = false
                                        this.customErrorLabel = '【' + item.chineseName + '】选项值不正确'
                                    }
                                }
                            }
                            // 复选框
                            if (item.fieldType == 'selectChecked') {
                                if (jsonForm[item.id] != '' && jsonForm[item.id] !=
                                    undefined && jsonForm[item.id] != '[]') {
                                    JSON.parse(jsonForm[item.id]).map(k => {
                                        let s = JSON.parse(item.checkBox).find(res => {
                                            return res.value == k
                                        })
                                        if (s == undefined) {
                                            this.customState = false
                                            this.customErrorLabel = '【' + item.chineseName +
                                                '】选项值不正确'
                                        }
                                    })
                                }
                            }
                        })
                        if (this.customState) {
                            if (this.uploadFlag) {
                                this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
                                    k.removeData('ok')
                                })
                                for (let key in jsonForm) {
                                    if (Number(key)) {
                                        this.customFiledList.forEach(item => {
                                            if (item.id == key && jsonForm[key] != null &&
                                                String(jsonForm[key]).length) {
                                                data.customFieldVos.push({
                                                    customFieldId: item.id,
                                                    value: jsonForm[key]
                                                })
                                            }
                                        })
                                    }
                                }
                                data = Object.assign({
                                    rate: jsonForm.rate,
                                    planedNumber: jsonForm.planedNumber,
                                    planedTime: jsonForm.planedTime,
                                }, data)
                                this.$emit('emitEditProcess', data, this.rowIndex)
                                this.editProcessVisible = false
                            } else {
                                this.utils.showMsg('正在上传，请稍后', 'warning')
                            }
                        } else {
                            this.utils.showMsg(this.customErrorLabel, 'error')
                        }
                    } else {
                        return false;
                    }
                })
            }
        }
    }
</script>

<style lang="less" scoped>
    .editProcess {
        .dialogBody {
            max-height: 600px;
            overflow-y: scroll;
            padding: 30px 230px 30px 40px;
            border: 1px solid #edeef3;
            background: #fbfbfb;
        }

        /deep/ .el-dialog__body {
            padding: 20px 60px;
        }

        /deep/ .el-dialog__footer {
            text-align: center;

            .el-button {
                padding: 7px 35px;
            }
        }
    }
</style>